/**
 * Build files
 * @author Wangtd
 */
const path = require("path");
const gulp = require('gulp');
const gulpif = require('gulp-if');
const clean = require('gulp-clean');
const cleanCss = require("gulp-clean-css");
const htmlmin = require("gulp-htmlmin");
const ngAnnotate = require('gulp-ng-annotate');
const uglifyes = require('uglify-es');
const uglifyComposer = require('gulp-uglify/composer');
const uglify = uglifyComposer(uglifyes, console);
const gulpSequence = require('gulp-sequence');

// clean
gulp.task('clean', function () {
    return gulp.src('dist', { read: false })
        .pipe(clean());
});

// build
gulp.task('build', function() {
    return gulp.src('app/**/*.*')
        // css
        .pipe(gulpif(function(file) {
            var filename = path.basename(file.path);
            return /\.css$/.test(filename) && !/[\.-]min\.css$/.test(filename);
        }, cleanCss({
            rebase: false,
            compatibility: '*',
            keepSpecialComments: '*'
        })))
        // html
        .pipe(gulpif(function(file) {
            return /\.html$/.test(path.basename(file.path));
        }, htmlmin({
            collapseWhitespace: true,
            conservativeCollapse: false,
            collapseInlineTagWhitespace: false,
            //preserveLineBreaks: true
            ignoreCustomFragments: [],
            minifyCSS: {
                compatibility: '*',
                keepSpecialComments: '*'
            }
        })))
        // angularjs
        .pipe(gulpif(function(file) {
            return /(app|config)\.js$/.test(file.path) ||
                   /\/app\/views\/.+\.js$/.test(file.path.replace(/\\/g, '/'));
        }, ngAnnotate()))
        // js
        .pipe(gulpif(function(file) {
            var filename = path.basename(file.path);
            return /\.js$/.test(filename) && !/[\.-](min|dist)\.js$/.test(filename);
        }, uglify()))
        .pipe(gulp.dest('dist'));
});

gulp.task('default', gulpSequence('clean', 'build'));
